<template>
  <div class="page reassign-list">
    <group v-if="mode === 'AX#' || mode === 'YX#'">
      <s-popup-picker title="调整次序" value="排序"
        cancelText="关闭"
        confirmText="确认互换"
        v-if="mode === 'AX#' || mode === 'YX#'"
        @on-hide="onHide"
        @on-shadow-change="changeSortValue"
        :show="sortShow"
        v-model="sortValue"
        :display-format="format"
        :data="[['顾问'], members1, ['与'], members2, [{name: '互换', value: 0}]]" >
      </s-popup-picker>
    </group>
    <group title="顾问列表">
      <template v-for="(member, index) in members">
        <cell :title="(index + 1) + ' ' + member.name" is-link :value="(mode === 'YX#' ? '分配比例' : '最大名单数') + member.max_list_count" :link="getLink(member)" ></cell>
      </template>
      <!-- <cell title="名单分配满后是否允许抢单" v-if="mode !== 'QD#' && typeof distributeConfig.is_allow_grab !== 'undefined'" @click.native="changeAllowGrab">
        <input slot="value" v-if="distributeConfig.is_allow_grab === 1" type="checkbox" checked />
        <input slot="value" v-else type="checkbox"/>
      </cell> -->
    </group>
    <!-- <panel header="客户分配说明" :list="list" :type="type"></panel> -->
  </div>
</template>

<script>
import Panel from 'vux/src/components/panel'
import Group from 'vux/src/components/group'
import Radio from 'vux/src/components/radio'
import Cell from 'vux/src/components/cell'
import XInput from 'vux/src/components/x-input'

import SPopupPicker from '../components/PopupPicker/Index'

import { mapActions, mapState } from 'vuex'
import Q from 'q'

export default {
  components: {
    Panel,
    Group,
    Radio,
    Cell,
    XInput,
    's-popup-picker': SPopupPicker
  },
  methods: {
    initMembers () {
      return Q.Promise((resolve, reject) => {
        this.getDistributeConfigUsers({
          team_id: this.teamId,
          distribute_type: encodeURIComponent(this.mode)
        }).then((response) => {
          if (response.data.errcode === 0) {
            this.sortMembers(response.data.results.data)
            this.temp = this.members2.splice(0, 1)
            resolve()
          } else {
            console.debug('系统出错!请联系管理员', response.data)
            resolve()
          }
        }).catch(() => {
          resolve()
        })
      })
    },
    onHide (type) {
      console.log(type)
      if (!type) {
        this.sortShow = false
      }

      if (type) {
        this.changeSortValue(this.sortValue)
      }
    },
    sortMembers (members) {
      const memberOpts = []
      this.members = this.sortObject(members, 'distribute_order')
      this.members.forEach((elem) => {
        memberOpts.push(Object.assign(elem, {name: elem.name, value: elem.suid}))
      })
      this.members1 = Object.assign([], memberOpts)
      this.members2 = Object.assign([], memberOpts)
    },
    changeOrder (data, suid, distributeOrder) {
      return Q.Promise((resolve, reject) => {
        data.forEach((elem, index) => {
          if (elem.suid === suid) {
            elem.distribute_order = distributeOrder
            elem.team_id = this.teamId
            elem.distribute_type = this.mode
            elem.id = this.distributeConfig.id

            this.saveCounselorDistributeConfig(elem).then((response) => {
              if (response.data.errcode === 0) {
                resolve()
              }
            })
          }
        })
      })
    },
    initDistributeConfig () {
      return Q.Promise((resolve, reject) => {
        this.getDistributeConfig(this.teamId)
          .then((response) => {
            if (response.data.errcode === 0) {
              const distributeConfig = response.data.results
              const defaultConfig = {is_allow_grab: distributeConfig.is_allow_grab}
              this.mode = distributeConfig.distribute_type
              this.initialMode = this.mode
              this.distributeConfig = Object.assign(distributeConfig, this.distributeConfig, defaultConfig)
              resolve()
            } else {
              resolve()
            }
          }).catch(() => {
            resolve()
          })
      })
    },
    initialize () {
      this.initMembers()
      .then(this.initDistributeConfig)
      .then(() => {
        this.$vux.loading.hide()
        this.init = true
      }).catch((err) => {
        this.$vux.loading.hide()
        console.log(err)
      })
    },
    changeAllowGrab () {
      this.distributeConfig.is_allow_grab = this.distributeConfig.is_allow_grab === 1 ? 0 : 1
      this.distributeConfig.team_id = this.teamId
      this.saveDistributeConfig(this.distributeConfig)
    },
    getLink (member) {
      const distributeType = this.$route.query.type
      const defaultQuery = {
        max_list_count: member.max_list_count,
        suid: member.suid,
        team_id: this.teamId,
        distribute_type: distributeType
      }
      return {
        name: 'max-limit',
        query: defaultQuery
      }
    },
    getDistributeOrder (suid) {
      const arr = this.members.filter((elem, index) => {
        return elem.suid === suid
      })
      return arr[0]['distribute_order']
    },
    hidePopup (value) {
      if (value === true) {
        console.log('hide')
        setTimeout(() => {
          this.sortShow = true
        }, 200)
      }
    },
    changeSortValue (value) {
      let removedIndex = false
      const sourceSuid = parseInt(value[1])
      const targetSuid = parseInt(value[3])
      const position = parseInt(value[4])
      const historyId = sourceSuid + '' + targetSuid
      this.members2.forEach((elem, index) => {
        if (sourceSuid === elem.value) {
          removedIndex = index
        }
      })
      if (removedIndex !== false && this.history[historyId + '_removed'] !== true) {
        let temp = false
        let origin = false
        if (Object.keys(this.temp).length) {
          origin = Object.assign({}, this.temp)
          if (origin[0].suid !== this.members2[removedIndex].suid) {
            temp = this.members2.splice(removedIndex, 1, origin[0])
            this.members2 = this.sortObject(this.members2, 'distribute_order')
          } else {
            temp = this.members2.splice(removedIndex, 1)
          }
        } else {
          temp = this.members2.splice(removedIndex, 1)
        }
        this.temp = temp
        this.history[historyId + '_removed'] = true
      }

      if (this.history[historyId] === true) {
        delete this.history[historyId]
        return
      }

      if (this.history[historyId + '_removed'] === true) {
        delete this.history[historyId + '_removed']
        return
      }

      if (this.source !== sourceSuid || this.source2 !== targetSuid) {
        // value[4] = -1
        this.sortValue = value
        this.history = {}
      } else {
        const tempOrder1 = this.getDistributeOrder(sourceSuid)
        const tempOrder2 = this.getDistributeOrder(targetSuid)

        if (position === 0) {
          this.changeOrder(this.members, sourceSuid, tempOrder2)
          this.changeOrder(this.members, targetSuid, tempOrder1)
          this.history[sourceSuid + '' + targetSuid] = true
        } else if (position === 1) {
        }

        this.sortMembers(this.members)
        // value[4] = -1
      }

      this.position = value[4]
      this.source = sourceSuid
      this.source2 = targetSuid
    },
    format () {
      // console.debug('format')
    },
    sortObject (array, key) {
      array.sort(function (a, b) {
        return a[key] - b[key]
      })
      return array
    },
    ...mapActions({
      'getTeam': 'getTeam',
      'getDistributeConfigUsers': 'getDistributeConfigUsers',
      'getDistributeConfig': 'getDistributeConfig',
      'saveDistributeConfig': 'saveDistributeConfig',
      'saveCounselorDistributeConfig': 'saveCounselorDistributeConfig'
    })
  },
  watch: {
    distributeConfig (value) {
      this.distributeConfig.is_allow_grab = parseInt(value.is_allow_grab)
    },
    sortValue (value) {
      // console.debug(JSON.stringify(value))
      // console.debug('sortValue')
    }
  },
  computed: {
    ...mapState({
      team: state => state.app.user.teams ? state.app.user.teams[0] : []
    })
  },
  mounted () {
    this.teamId = this.$route.query.team_id
    this.distributeConfig = this.$route.query
    const title = this.$route.query.title
    this.mode = this.$route.query.type
    this.$vux.loading.show({text: 'loading'})
    this.callJsApi('biz.navigation.setTitle', { title: title || '' })
    this.initialize()
  },
  data () {
    return {
      mode: '',
      init: false,
      initialMode: '',
      selectedMode: {},
      distributeConfig: {},
      members: [],
      sortShow: false,
      type: '2',
      sortValue: [],
      members1: [],
      members2: [],
      history: {},
      temp: {},
      query: {},
      list: [{
        src: 'http://placeholder.qiniudn.com/60x60/3cc51f/ffffff',
        title: '',
        desc: '所属顾问的客户名单退回团队公海或者被分配给其他顾问，则其客户名单数减少'
        // url: '/component/cell'
      }, {
        src: 'http://placeholder.qiniudn.com/60x60/3cc51f/ffffff',
        title: '',
        desc: '所属顾问的客户名单在校务系统成交课程订单，则其客户名单数减少'
      }],
      footer: {
        title: '查看更多',
        url: 'http://vux.li'
      }
    }
  }
}
</script>
<style lang="less">
  .reassign-list {
    .weui-cell__ft {
      max-width: 210px;
    }
  }
</style>
